﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using ETRoboConTrakingSystem;
using ETRobocon.RaceTraking.GamePresentation;

namespace ETRobocon.RaceTraking.GameManagement
{
    /// <summary>
    /// RoundMgmtUserControl.xaml の相互作用ロジック
    /// </summary>
    public partial class RoundMgmtUserControl : UserControl
    {
        private SwitchLightStatus _switchLightStatus;
        public SwitchLightStatus SwitchLightStatus
        {
            get { return _switchLightStatus; }
            set
            {
                _switchLightStatus = value;
            }
        }
        public ISwitchLightStatusNotifier switchLightStatusNotifier { get; set; }

        private TopTurnControlWindow _turnCtrlWindow;
        public TopTurnControlWindow TurnCtrlWindow
        {
            get { return _turnCtrlWindow; }
            set { _turnCtrlWindow = value; }
        }

        public RoundMgmtUserControl()
        {
            InitializeComponent();
            WSContestList list = this.Resources["contestList"] as WSContestList;
            list.UpdateContents();
        }

        private WSRound _currentRound = new WSRound();
        public WSRound CurrentRound
        {
            get { return _currentRound; }
            set { _currentRound = value; }
        }
        public WSTeamEntry InCourceRunner
        {
            get { return this.Resources["inCourceRunner"] as WSTeamEntry; }
            set
            {
                this.Resources["inCourceRunner"] = value;
            }
        }
        public WSTeamEntry OutCourceRunner
        {
            get { return this.Resources["outCourceRunner"] as WSTeamEntry; }
            set
            {
                this.Resources["outCourceRunner"] = value;
            }
        }
        private WSTurn _currentTurn = null;
        public WSTurn CurrentTurn
        {
            get { return _currentTurn; }
            set { _currentTurn = value; }
        }

        private IBonusCheckPointsBuilder _icBCPBuilder = null;
        public IBonusCheckPointsBuilder InCourseBCPBuilder
        {
            set
            {
                _icBCPBuilder = value;
            }
        }

        private IBonusCheckPointsBuilder _ocBCPBuilder = null;
        public IBonusCheckPointsBuilder OutCourseBCPBuilder
        {
            set
            {
                _ocBCPBuilder = value;
            }
        }

        private IRaceTrackingPresentation _presentationWindow;
        public IRaceTrackingPresentation PresentationWindow
        {
            set
            {
                _presentationWindow = value;

            }
        }

        private TurnMgmtUserControl _turnMgmtControlPanel;
        public TurnMgmtUserControl TurnMgmtControlPanel
        {
            set
            {
                _turnMgmtControlPanel = value;
            }
        }

        private void buttonRoundStart_Click(object sender, RoutedEventArgs e)
        {
            if (listBoxRound.SelectedItem != null)
            {
                var rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
                //                using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
                {
                    WSRound round = listBoxRound.SelectedItem as WSRound;
                    if (MessageBox.Show(round.Parent.Name + "[ラウンド:" + round.No + "]を開始しますか？", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.No)
                    {
                        return;
                    }
                    if (MessageBox.Show(@"OKをクリックするとラウンド:" + round.No + @"の競技結果が記録されている場合、結果が全消去されます。継続しますか？", @"警告", MessageBoxButton.OKCancel, MessageBoxImage.Warning, MessageBoxResult.Cancel) == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                    int roundId;
                    if (rm.StartRound(out roundId, round.Parent.ID, round.No))
                    {
                        round.ID = roundId;
                        SetupRoundInfo(round);
                        ShowPresentationWindow();

                        ETRoboConTrakingSystem.ETRoboConRM.BonusSpecInfo[] icBSs;
                        if (rm.GetBonusSpecInfo(out icBSs, _currentRound.Parent.ID, ETRoboConTrakingSystem.ETRoboConRM.CourseName.IN))
                        {
                            var bsList = new WSBonusSpecList();
                            foreach (var bs in icBSs)
                            {
                                var wsbs = new WSBonusSpec(_currentRound.Parent);
                                wsbs.ID = bs.GameCourseSpecId;
                                wsbs.Name = bs.Name;
                                wsbs.ShortCut = bs.ShortName;
                                wsbs.Descrip = bs.Specification;
                                wsbs.Point = bs.Point;
                                bsList.Add(wsbs);
                            }
                            this._icBCPBuilder.BuildupClearMarks(bsList);
                        }
                        ETRoboConTrakingSystem.ETRoboConRM.BonusSpecInfo[] ocBSs;
                        if (rm.GetBonusSpecInfo(out ocBSs, _currentRound.Parent.ID, ETRoboConTrakingSystem.ETRoboConRM.CourseName.OUT))
                        {
                            var bsList = new WSBonusSpecList();
                            foreach (var bs in ocBSs)
                            {
                                var wsbs = new WSBonusSpec(_currentRound.Parent);
                                wsbs.ID = bs.GameCourseSpecId;
                                wsbs.Name = bs.Name;
                                wsbs.ShortCut = bs.ShortName;
                                wsbs.Descrip = bs.Specification;
                                wsbs.Point = bs.Point;
                                bsList.Add(wsbs);
                            }
                            this._ocBCPBuilder.BuildupClearMarks(bsList);
                        }

                        this._turnCtrlWindow.Show();
                        this._turnCtrlWindow.ResetShow();
                    }
                    else
                    {
                        MessageBox.Show("ラウンドがスタートできませんでした。ラウンド、走行順が定義されていない可能性があります");
                    }
                }
                rm.Close();
            }
        }

        private bool _hasSetupBCPBuilder = false;
        private void SetupRoundInfo(WSRound round)
        {
            _currentRound.ID = round.ID;
            _currentRound.Parent = round.Parent;
            _currentRound.No = round.No;
            textBlockGameID.Text = round.Parent.ID.ToString();
            textBlockGameName.Text = round.Parent.Name;
            textBlockRoundNo.Text = round.No.ToString();

//            RoundInfo ri = this._presentationWindow.MainControl.CurrentRoundInfo;
            RoundInfo ri = this._presentationWindow.CurrentRoundInfo;
            ri.GameName = round.Parent.Name;
            ri.RoundNo = round.No;

            if (!_hasSetupBCPBuilder)
            {
                if (_icBCPBuilder != null)
                {
                    _icBCPBuilder.SetupBonusSpecChecks(WSRunner.CourseName.IN, round.Parent.InCourseBonusSpecs);
                    _icBCPBuilder.TargetRunnerStatus = _presentationWindow.InCourseRunnerStatus;
                }
                if (_ocBCPBuilder != null)
                {
                    _ocBCPBuilder.SetupBonusSpecChecks(WSRunner.CourseName.OUT, round.Parent.OutCourseBonusSpecs);
                    _ocBCPBuilder.TargetRunnerStatus = _presentationWindow.OutCourseRunnerStatus;
                }
                _hasSetupBCPBuilder = true;
            }

            if (switchLightStatusNotifier!=null)
            {
                switchLightStatusNotifier.Reset();
            }
        }

        private void ShowPresentationWindow()
        {
            var preW = this._presentationWindow as Window;
            preW.Show();

            // Show presentation window when 2nd display existed.
            if (System.Windows.Forms.Screen.AllScreens.Count() > 1)
            {
                foreach (System.Windows.Forms.Screen scr in System.Windows.Forms.Screen.AllScreens)
                {
                    if (!scr.Primary)
                    {
                        //                                    this._presentationWindow.Top = scr.Bounds.Top;
                        preW.Left = scr.Bounds.X;
                    }
                }
            }
            preW.WindowState = WindowState.Maximized;


        }

        private void buttonRoundCount_Click(object sender, RoutedEventArgs e)
        {
            if (listBoxGame.SelectedItem != null)
            {
                var rm = new ETRoboConRM.ETRoboConRaceMgmtClient();
                //                using (WSRaceMgmt.RaceMgmt rm = new WSRaceMgmt.RaceMgmt())
                {
                    WSGame game = listBoxGame.SelectedItem as WSGame;
                    int roundId;
                    int roundNo;
                    if (rm.GetCurrentRound(out roundNo, out roundId, game.ID))
                    {
                        WSRound round = null;
                        for (int i = 0; i < listBoxRound.Items.Count; i++)
                        {
                            WSRound candidate = listBoxRound.Items[i] as WSRound;
                            if (candidate.No == roundNo)
                            {
                                candidate.ID = roundId;
                                round = candidate;
                                break;
                            }
                        }
                        if (round != null && rm.ContinueRound(out roundId, game.ID))
                        {
                            SetupRoundInfo(round);
                            ShowPresentationWindow();
                            this._turnCtrlWindow.Show();

                            ETRoboConTrakingSystem.ETRoboConRM.BonusSpecInfo[] icBSs;
                            if (rm.GetBonusSpecInfo(out icBSs, _currentRound.Parent.ID, ETRoboConTrakingSystem.ETRoboConRM.CourseName.IN))
                            {
                                var bsList = new WSBonusSpecList();
                                foreach (var bs in icBSs)
                                {
                                    var wsbs = new WSBonusSpec(_currentRound.Parent);
                                    wsbs.ID = bs.GameCourseSpecId;
                                    wsbs.Name = bs.Name;
                                    wsbs.ShortCut = bs.ShortName;
                                    wsbs.Descrip = bs.Specification;
                                    wsbs.Point = bs.Point;
                                    bsList.Add(wsbs);
                                }
                                this._icBCPBuilder.BuildupClearMarks(bsList);
                            }
                            ETRoboConTrakingSystem.ETRoboConRM.BonusSpecInfo[] ocBSs;
                            if (rm.GetBonusSpecInfo(out ocBSs, _currentRound.Parent.ID, ETRoboConTrakingSystem.ETRoboConRM.CourseName.OUT))
                            {
                                var bsList = new WSBonusSpecList();
                                foreach (var bs in ocBSs)
                                {
                                    var wsbs = new WSBonusSpec(_currentRound.Parent);
                                    wsbs.ID = bs.GameCourseSpecId;
                                    wsbs.Name = bs.Name;
                                    wsbs.ShortCut = bs.ShortName;
                                    wsbs.Descrip = bs.Specification;
                                    wsbs.Point = bs.Point;
                                    bsList.Add(wsbs);
                                }
                                this._ocBCPBuilder.BuildupClearMarks(bsList);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("中途半端に中断しているラウンドは無いがぜよ");
                    }
                }
                rm.Close();
            }
        }
    }
}
